 /**
 * Description: 盘点计划
 * @author:hunter
 * @since:1.0.0
 *
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2018-04-08   hunter       1.0.0     Initial
 */
package com.metro.paperless.app.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.metro.core.annotation.BusinessDesc;
import com.metro.core.page.Page;
import com.metro.core.vo.JsonResult;
import com.metro.core.vo.QueryParams;
import com.metro.core.vo.ResultCode;
import com.metro.core.vo.inf.IResult;
import com.metro.paperless.app.beans.vo.AppCheckDetail;
import com.metro.paperless.app.beans.vo.AppCheckDetailForm;
import com.metro.paperless.app.beans.vo.AppCheckPlan;
import com.metro.paperless.app.service.inf.IAppCheckDetailService;
import com.metro.paperless.app.service.inf.IAppCheckPlanService;
import com.metro.paperless.biz.beans.vo.BizInsideOrg;
import com.metro.paperless.biz.service.inf.IBizInsideOrgService;
import com.metro.paperless.common.beans.constant.DicTypeEnum;
import com.metro.paperless.common.beans.constant.PropertiesEnum;
import com.metro.paperless.common.utils.CreateBarCodeUtils;
import com.metro.paperless.common.utils.DicUtil;
import com.metro.paperless.common.utils.IdGen;
import com.metro.paperless.common.utils.UserUtil;
import com.metro.paperless.sys.beans.vo.SysDeparment;
import com.metro.paperless.sys.beans.vo.SysUser;
import com.metro.paperless.sys.service.inf.ISysDeparmentService;
import com.metro.paperless.sys.service.inf.ISysUserService;
import com.metro.paperless.web.controller.BaseController;
import com.metro.utils.DateUtil;
import com.metro.utils.StringUtil;
import com.weslink.qsign.util.FtlUtil;

 /**
 * 盘点计划<br>
 *
 * @author:hunter
 * @since:1.0.0
 * @version [1.0.0, 2018-04-08]
 */
@Controller
@RequestMapping("/appCheckPlan")
public class AppCheckPlanController extends BaseController {
    //菜单编码
    private static final String menuCode = "APP_CHECK_PLAN";
    //模块描述
    private static final String MODULE_DESC = "盘点计划";
    @Autowired
    private IAppCheckPlanService appcheckplanService;
     @Autowired
     private IBizInsideOrgService bizInsideOrgService;
     @Autowired
     private ISysDeparmentService deparmentService;
     @Autowired
     private IAppCheckDetailService checkDetailService;
     @Autowired
     private ISysUserService userService;
    @Override
    protected String getViewDir() {
        return "app/check/";
    }
    
    /**
     * 去查询盘点计划
     * 
     * @param appcheckplan 盘点计划页面表单对象
     * @param page 分页配置
     * @return 结果视图
     * @author hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "查询盘点计划列表")
    @RequiresPermissions(menuCode + ":view")
    @SuppressWarnings("all")
    @RequestMapping(value = "list", method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView list(AppCheckPlan appcheckplan) {
        ModelAndView mav = new ModelAndView();
        try {
            mav.setViewName(getView("appcheckplan_list"));
            mav.addObject("searchEntity", appcheckplan);
        } catch (Exception ex) {
            log.error("查询盘点计划出错", ex);
            mav.addObject("ex", ex);
            mav.setViewName("/commons/error/error");
        }
        return mav;
    }

    /**
     * 查询盘点计划
     *
     * @param appcheckplan 盘点计划页面表单对象
     * @param page 分页配置
     * @return 结果视图
     * @author hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "查询盘点计划列表")
    @RequiresPermissions(menuCode + ":view")
    @SuppressWarnings("all")
    @RequestMapping(value = "dolist", method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JsonResult dolist(AppCheckPlan appcheckplan, Page page, QueryParams<AppCheckPlan> queryParams) {
        JsonResult jr = new JsonResult();
        try {
            queryParams.setPaging(page);
            queryParams.setEntity(appcheckplan);
            queryParams.setOrderColumn("a.id desc"); //添加排序
            PageInfo<AppCheckPlan> pageInfo = appcheckplanService.queryForPage(queryParams);
            jr.setData(pageInfo);
            jr.setResult(ResultCode.SUCCESS);
        } catch (Exception ex){
            log.error("查询盘点计划出错",ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }

    /**
     * 去新增盘点计划
     * 
     * @return 结果视图
     * @author hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "去新增盘点计划")
    @RequiresPermissions(menuCode + ":add")
    @RequestMapping(value = "create")
    public ModelAndView createForm(Model model, HttpServletRequest request){
        ModelAndView mav = new ModelAndView();
        //生成随机编号
        //编号生成规则为IT+年+月+日+四位随机数  即 IT+18+03+04+1234（不可编辑、唯一)
        String shortCode = "IT" + IdGen.getBarCode();
        //生成条码
        String barCodeImg = CreateBarCodeUtils.generateBaseMsg(shortCode);
        mav.addObject("barCode", shortCode);
        mav.addObject("barCodeImg", barCodeImg);
        SysUser user = userService.getById(UserUtil.getCurrUser().getUserId());
        SysDeparment deparment = deparmentService.getById(user.getDepartmentId());
        mav.addObject("deparment", deparment);
        mav.addObject("user", user);
        try {
            initCreateOrUpdateFrom(mav, "create",null);
        } catch (Exception ex) {
            log.error("去新增盘点计划出错", ex);
            mav.addObject("ex", ex);
            mav.setViewName("/commons/error/error");
        }
        return mav;
    }
    
    /**
     * 初始化新增修改盘点计划所需参数
     * @author hunter
     */
    private void initCreateOrUpdateFrom(ModelAndView mav, String action,String actionType){
        mav.addObject("checkStatuss", DicUtil.getLabelValueList(DicTypeEnum.CHECK_STATUS));
        mav.addObject("action", action);
        String page = "appcheckplan_draft_form";
        if(actionType!=null && actionType.equals("check")){
            page = "appcheckplan_check_form";
        }
        mav.setViewName(getView(page));
    }


     @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "物资出借单打印")
     @RequiresPermissions(menuCode + ":add")
     @RequestMapping(value = "checkPrint/{checkId}")
     public ModelAndView checkPrint(Model model, HttpServletRequest request,@PathVariable String checkId){
         ModelAndView mav = new ModelAndView();
         try{
             //盘点物资明细
             List<AppCheckDetail> appCheckDetailList = checkDetailService.queryListByCheckId(Long.valueOf(checkId));
             int checkMats = appCheckDetailList.size();
             //查询物资盘点记录
             AppCheckPlan entity = appcheckplanService.getById(Long.valueOf(checkId));

             String barCodeImg = CreateBarCodeUtils.generateBaseMsg(entity.getCheckCode());
             Map<String, Object> data=new HashMap<>();
             data.put("matCheckList", appCheckDetailList);
             data.put("checkMats", checkMats);
             data.put("entity",entity);
             data.put("barCodeImg", "data:image/png;base64,"+barCodeImg);
             String rootDir = PropertiesEnum.getPropertyValue(PropertiesEnum.FILE_UPLOAD_ROOT);
             FtlUtil.tempalteToFile("check.ftl", data, rootDir+"/"+entity.getIdStr()+".pdf");

             mav.addObject("entity",entity);
             mav.addObject("barCodeImg", "data:image/png;base64,"+barCodeImg);
             String port = PropertiesEnum.getPropertyValue(PropertiesEnum.PAD_PATHPORT);
             mav.addObject("port",port);
             mav.addObject("appCheckDetailList",appCheckDetailList);
             mav.addObject("checkMats",checkMats);
             mav.setViewName(getView("appcheckplan_print"));
         }catch(Exception ex){
             log.error("物资出借单打印失败", ex);
             mav.addObject("ex", ex);
             mav.setViewName("/commons/error/error");
         }

         return mav;
     }
     
     
     @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "物资出借单查看")
     @RequiresPermissions(menuCode + ":add")
     @RequestMapping(value = "checkPrintSigned/{checkId}")
     public ModelAndView checkPrintSigned(Model model, HttpServletRequest request,@PathVariable String checkId){
         ModelAndView mav = new ModelAndView();
         try{
             //盘点物资明细
             List<AppCheckDetail> appCheckDetailList = checkDetailService.queryListByCheckId(Long.valueOf(checkId));
             int checkMats = appCheckDetailList.size();
             //查询物资盘点记录
             AppCheckPlan entity = appcheckplanService.getById(Long.valueOf(checkId));

             String barCodeImg = CreateBarCodeUtils.generateBaseMsg(entity.getCheckCode());
             Map<String, Object> data=new HashMap<>();
             data.put("matCheckList", appCheckDetailList);
             data.put("checkMats", checkMats);
             data.put("entity",entity);
             data.put("barCodeImg", "data:image/png;base64,"+barCodeImg);
             String rootDir = PropertiesEnum.getPropertyValue(PropertiesEnum.FILE_UPLOAD_ROOT);
             FtlUtil.tempalteToFile("check.ftl", data, rootDir+"/"+entity.getIdStr()+".pdf");

             mav.addObject("entity",entity);
             mav.addObject("barCodeImg", "data:image/png;base64,"+barCodeImg);
             String port = PropertiesEnum.getPropertyValue(PropertiesEnum.PAD_PATHPORT);
             mav.addObject("port",port);
             mav.addObject("appCheckDetailList",appCheckDetailList);
             mav.addObject("checkMats",checkMats);
             mav.setViewName(getView("appcheckplan_print_signed"));
         }catch(Exception ex){
             log.error("物资出借单打印失败", ex);
             mav.addObject("ex", ex);
             mav.setViewName("/commons/error/error");
         }

         return mav;
     }


     /**
     * 新增盘点计划
     * 
     * @param entity 盘点计划页面表单对象
     * @param request 请求对象
     * @return 结果视图
     * @author hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "新增盘点计划")
    @RequiresPermissions(menuCode + ":add")
    @RequestMapping(value = "save", method = { RequestMethod.POST})
    @ResponseBody
    public JsonResult saveAppCheckPlan(AppCheckPlan entity, AppCheckDetailForm itemEntity , HttpServletRequest request) {
        JsonResult jr = new JsonResult();
        try {
            List<AppCheckPlan> list = appcheckplanService.queryForList(entity);
            SysUser user = userService.getById(UserUtil.getCurrUser().getUserId());
            if(list == null || list.size()<1 ){
                if(StringUtil.isBlank(entity.getPlanName())){
                    entity.setPlanName(DateUtil.formatDateforUS(new Date(),"yyyy年MM月dd日")+"盘点计划");
                }
                entity.setInitiatorName(user.getName());
                entity.setInitiatorId(user.getId());
                jr = appcheckplanService.save(itemEntity, entity); //保存盘点记录和出库明细
                Long planId  = (Long) jr.getData();
                jr.setResult(jr);
                jr.setData(planId);
            }else{
                jr.setResult(ResultCode.ERROR);
                jr.setMsg("当前出库单已保存");
            }
            log.debug("新增盘点计划成功【{}】", entity);
        } catch (Exception ex) {
            log.error("新增盘点计划出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }

    /**
     * 删除盘点计划
     * 
     * @param id 盘点计划页面表单对象唯一标识
     * @param request 请求对象
     * @return 结果视图
     * @author hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "删除盘点计划")
    @RequiresPermissions(menuCode + ":delete")
    @RequestMapping(value = "delete/{id}", method = { RequestMethod.DELETE })
    @ResponseBody
    public JsonResult delete(@PathVariable String id, HttpServletRequest request){
        JsonResult jr = new JsonResult();
        try {
            log.debug("删除盘点计划id={}",id);
            IResult codeMsg = appcheckplanService.deleteByIds(id);
            jr.setResult(codeMsg);
        } catch (Exception ex) {
            log.error("删除盘点计划出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }
    
    /**
     * 去修改盘点计划
     * 
     * @param id 盘点计划页面表单对象唯一标识
     * @param request 请求对象
     * @return 结果视图
     * @author hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "去修改盘点计划")
    @RequiresPermissions(menuCode + ":edit")
    @RequestMapping(value = "edit/{id}/{action}", method = { RequestMethod.GET})
    public ModelAndView updateForm(@PathVariable Long id,@PathVariable String action, HttpServletRequest request){
        ModelAndView mav = new ModelAndView();
        try {
            // 查询物资盘点记录
            AppCheckPlan entity = appcheckplanService.getById(id);
            // 根据盘点单号获取盘点明细
            List<AppCheckDetail> list = checkDetailService.queryListByCheckId(id);
            String barCodeImg = CreateBarCodeUtils.generateBaseMsg(entity.getCheckCode());

            mav.addObject("barCode", entity.getCheckCode());
            mav.addObject("barCodeImg", barCodeImg);

            List<BizInsideOrg> orgList = bizInsideOrgService.queryForList(new BizInsideOrg());
            mav.addObject("orgList", orgList);

            SysUser user = userService.getById(UserUtil.getCurrUser().getUserId());
            SysDeparment deparment = deparmentService.getById(user.getDepartmentId());
            mav.addObject("deparment", deparment);
            mav.addObject("user", user);
            mav.addObject("checkMats",list.size());

            mav.addObject("appCheckDetailList", list);
            mav.addObject("entity", entity);

            initCreateOrUpdateFrom(mav,"edit",action);
        } catch (Exception ex) {
            log.error("去修改盘点计划", ex);
            mav.setView(new RedirectView("list"));
        }
        return mav;
    }

    /**
     * 修改盘点计划
     * 
     * @param entity 盘点计划页面表单对象
     * @param request 请求对象
     * @return 结果视图
     * @author hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "修改盘点计划")
    @RequiresPermissions(menuCode + ":edit")
    @RequestMapping(value = "update", method = { RequestMethod.POST})
    @ResponseBody
    public JsonResult updateAppCheckPlan(AppCheckDetailForm itemEntity,AppCheckPlan entity, HttpServletRequest request) {
        JsonResult jr = new JsonResult();
        try {
            IResult res = appcheckplanService.update(itemEntity,entity);
            jr.setData(entity.getId());
            jr.setResult(res);
            log.debug("修改盘点计划成功【{}】", entity);
        } catch (Exception ex) {
            log.error("修改盘点计划出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }
    /**
     * 保存盘点数据
     *
     * @param entity 盘点计划页面表单对象
     * @param request 请求对象
     * @return 结果视图
     * @author hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "修改盘点计划")
    @RequiresPermissions(menuCode + ":edit")
    @RequestMapping(value = "updateCheck", method = { RequestMethod.POST})
    @ResponseBody
    public JsonResult updateCheckDetail(AppCheckDetailForm itemEntity,AppCheckPlan entity, HttpServletRequest request) {
        JsonResult jr = new JsonResult();
        try {
            IResult res = appcheckplanService.updateCheck(itemEntity,entity);
            jr.setData(entity.getId());
            jr.setResult(res);
            log.debug("修改盘点明细成功【{}】", entity);
        } catch (Exception ex) {
            log.error("修改盘点明细出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }

    /**
     * 去查看盘点计划
     * 
     * @param id 盘点计划页面表单对象唯一标识
     * @return 结果视图
     * @author hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "去查看盘点计划详情")
    @RequiresPermissions(menuCode + ":view")
    @RequestMapping(value = "info/{id}", method = { RequestMethod.GET })
    public ModelAndView info(@PathVariable Long id) {
        ModelAndView mav= new ModelAndView();
        try {
            mav.addObject("checkId",id);
            mav.setViewName(getView("appcheckplan_info"));
        } catch (Exception ex) {
            log.error("查看盘点计划出错", ex);
        }
        return mav;
        
    }

     /**
      * 去出库单展示页，准备签署
      *
      * @return 结果视图
      * @author Hunter
      * @since [1.0.0]
      * @version [1.0.0, 2018-04-10]
      */
     @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "去入库单展示页，准备签署")
     @RequiresPermissions(menuCode + ":add")
     @RequestMapping(value = "checkSign/{checkId}")
     public ModelAndView outSignForm(Model model, HttpServletRequest request,@PathVariable String checkId){
         ModelAndView mav = new ModelAndView();
         try {
             Map<String,String> resuleMap = createContract(checkId);
             mav.addObject("content",resuleMap);

             Map redoMap= new HashMap();
             redoMap.put("cmd","redo");
             redoMap.put("seq_id",checkId);
             String redo = JSONObject.toJSONString(redoMap);
             mav.addObject("redo",redo);

             Map homeMap= new HashMap();
             homeMap.put("cmd","home");
             homeMap.put("seq_id",checkId);
             String home = JSONObject.toJSONString(homeMap);
             mav.addObject("home",home);

             Map getMap= new HashMap(); //获取图片
             getMap.put("cmd","get");
             getMap.put("seq_id",checkId);
             String get = JSONObject.toJSONString(getMap);
             mav.addObject("get",get);

             Map cancelMap= new HashMap(); //取消
             cancelMap.put("cmd","cancel");
             cancelMap.put("seq_id",checkId);
             String cancel = JSONObject.toJSONString(cancelMap);
             model.addAttribute("cancel",cancel);

             //盘点物资明细
             List<AppCheckDetail> appCheckDetailList = checkDetailService.queryListByCheckId(Long.valueOf(checkId));
             int checkMats = appCheckDetailList.size();
             //查询物资盘点记录
             AppCheckPlan entity = appcheckplanService.getById(Long.valueOf(checkId));

             String barCodeImg = CreateBarCodeUtils.generateBaseMsg(entity.getCheckCode());
             Map<String, Object> data=new HashMap<>();
             data.put("matCheckList", appCheckDetailList);
             data.put("checkMats", checkMats);
             data.put("entity",entity);
             data.put("barCodeImg", "data:image/png;base64,"+barCodeImg);
             String rootDir = PropertiesEnum.getPropertyValue(PropertiesEnum.FILE_UPLOAD_ROOT);
             FtlUtil.tempalteToFile("check.ftl", data, rootDir+"/"+entity.getIdStr()+".pdf");

             mav.addObject("entity",entity);
             mav.addObject("barCodeImg", "data:image/png;base64,"+barCodeImg);
             String port = PropertiesEnum.getPropertyValue(PropertiesEnum.PAD_PATHPORT);
             mav.addObject("port",port);
             mav.addObject("appCheckDetailList",appCheckDetailList);
             mav.addObject("checkMats",checkMats);
             mav.setViewName(getView("appcheckplan_sign"));
         } catch (Exception ex) {
             log.error("去出库单展示页，准备签署", ex);
             mav.addObject("ex", ex);
             mav.setViewName("/commons/error/error");
         }
         return mav;
     }

     /**
      * 签署成功保存文件
      * @param entity
      * @param signName
      * @param request
      * @return
      */
     @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "确认物资入库")
     @RequiresPermissions(menuCode + ":add")
     @RequestMapping(value = "commitCheck", method = { RequestMethod.POST})
     @ResponseBody
     public JsonResult commitOut(AppCheckPlan entity,String signName, HttpServletRequest request) {
         JsonResult jr = new JsonResult();
         try {
             Map<String,Object> data = new HashMap<>();
             String id = entity.getIdStr();
             //盘点物资
             List<AppCheckDetail>  appCheckDetails = checkDetailService.queryListByCheckId(Long.valueOf(id));
             // 查询物资盘点记录
             entity = appcheckplanService.getById(Long.valueOf(id));
             //操作数据
             entity.setCheckStatus("3");
             entity.setInitiatorTime(new Date());
             entity.setSignName(signName);

             data.put("signname",signName);
             data.put("checkMats", appCheckDetails.size());
             data.put("matCheckList", appCheckDetails);
             data.put("entity",entity);
             data.put("barCodeImg", "data:image/png;base64,"+ CreateBarCodeUtils.generateBaseMsg(entity.getCheckCode()));
             String rootDir = PropertiesEnum.getPropertyValue(PropertiesEnum.FILE_UPLOAD_ROOT);
             FtlUtil.tempalteToFile("check.ftl", data, rootDir+"/"+entity.getIdStr()+"-signed.pdf");

             jr.setResult(appcheckplanService.update(entity));
             jr.setData(entity.getId());
             log.debug("物资入库成功【{}】", entity);
         } catch (Exception ex) {
             log.error("物资入库出错", ex);
             jr.setResult(ResultCode.ERROR);
         }
         return jr;
     }
    
}
